package com.huhao.wshare.Friends;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.huhao.wshare.Config.GET_FRIEND_LIST;

// 导入分离后的类
import com.huhao.wshare.LoginActivity;
import com.huhao.wshare.R;
import com.huhao.wshare.Refreshable;

public class FriendsFragment extends Fragment implements Refreshable {

    private RecyclerView recyclerView;
    private FriendAdapter friendAdapter;
    private String token;
    private OkHttpClient client = new OkHttpClient();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件
        View view = inflater.inflate(R.layout.fragment_friends, container, false);

        // 初始化 RecyclerView
        recyclerView = view.findViewById(R.id.recyclerView_friends);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 添加系统默认分隔线
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL);
        recyclerView.addItemDecoration(dividerItemDecoration);

        // 初始化适配器并设置给 RecyclerView
        friendAdapter = new FriendAdapter(new ArrayList<>());
        recyclerView.setAdapter(friendAdapter);

        // 从 SharedPreferences 中获取 token
        SharedPreferences sp = requireActivity().getSharedPreferences("user_prefs", requireContext().MODE_PRIVATE);
        token = sp.getString("token", null);

        if (token != null) {
            // 获取好友列表
            fetchFriendList();
        } else {
            // 用户未登录，跳转到登录页
            startActivity(new Intent(requireActivity(), LoginActivity.class));
            requireActivity().finish();
        }

        // 为搜索按钮添加点击事件
        ImageView searchButton = view.findViewById(R.id.search_button);
        searchButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), SearchActivity.class);
            startActivity(intent);
        });

        // 为添加按钮添加点击事件
        ImageView addButton = view.findViewById(R.id.add_button);
        addButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AddFriendActivity.class);
            startActivity(intent);
        });

        return view;
    }

    @Override
    public void refresh() {
        fetchFriendList();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (token != null) {
            fetchFriendList();
        }
    }


    private void fetchFriendList() {
        // 构建请求头，包含 Authorization
        Request request = new Request.Builder()
                .url(GET_FRIEND_LIST)
                .get()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        // 发送网络请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    final String respStr = response.body().string();
                    requireActivity().runOnUiThread(() -> handleFriendListResponse(respStr));
                } else {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireContext(), "获取好友列表失败，请稍后重试", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

    private void handleFriendListResponse(String respStr) {
        try {
            JSONObject json = new JSONObject(respStr);
            int code = json.optInt("code");
            if (code == 200) {
                JSONArray data = json.optJSONArray("data");
                if (data != null) {
                    List<Friend> newFriendList = new ArrayList<>();
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject friendJson = data.getJSONObject(i);
                        int id = friendJson.optInt("friendId");
                        String account = friendJson.optString("account");
                        String username = friendJson.optString("username");
                        String signs = friendJson.optString("signs");
                        String remark = friendJson.optString("remark");
                        String avatar = friendJson.optString("avatar");
                        String gender = friendJson.optString("gender");
                        newFriendList.add(new Friend(id, account, username, signs, remark, avatar, gender));
                    }
                    friendAdapter.updateFriendList(newFriendList);
                }
            } else {
                Toast.makeText(requireContext(), json.optString("message"), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(requireContext(), "解析好友列表失败", Toast.LENGTH_SHORT).show();
            Log.e("FriendsFragment", "解析 JSON 失败", e);
        }
    }
}